#!/usr/bin/env python3
"""
手动导入用户在Shopify上传的新商品
"""

import os
import sys
import logging
from datetime import datetime

# 添加当前目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 导入必要的模块
import shopify
from dotenv import load_dotenv
from database.connection import async_session
from database.models import Product
import asyncio

# 加载环境变量
load_dotenv()

def get_shopify_config():
    """获取Shopify配置"""
    return {
        'api_key': os.getenv("SHOPIFY_API_KEY", ""),
        'api_secret': os.getenv("SHOPIFY_API_SECRET", ""),
        'store_url': os.getenv("SHOPIFY_STORE_URL", ""),
        'access_token': os.getenv("SHOPIFY_ACCESS_TOKEN", "")
    }

def setup_shopify_connection():
    """设置Shopify连接"""
    config = get_shopify_config()
    
    logger.info("设置Shopify连接...")
    logger.info(f"Store URL: {config['store_url']}")
    
    try:
        shopify.Session.setup(api_key=config['api_key'], secret=config['api_secret'])
        session = shopify.Session(config['store_url'], "2023-10", config['access_token'])
        shopify.ShopifyResource.activate_session(session)
        logger.info("Shopify连接设置成功")
        return True
    except Exception as e:
        logger.error(f"Shopify连接设置失败: {e}")
        import traceback
        traceback.print_exc()
        return False

def get_shopify_products(limit=50):
    """从Shopify获取商品列表"""
    try:
        logger.info(f"尝试获取最多 {min(limit, 100)} 个Shopify商品")
        products = shopify.Product.find(limit=min(limit, 100))
        logger.info(f"成功获取到 {len(products)} 个商品")
        
        shopify_products = []
        for product in products:
            product_dict = product.to_dict()
            # 提取必要信息
            shopify_product = {
                'id': str(product_dict['id']),
                'title': product_dict.get('title', '未命名'),
                'description': product_dict.get('body_html', '').replace('<[^>]*>', '').strip() or '无描述',
                'price': 0.0,
                'variants': [],
                'status': product_dict.get('status', 'active')
            }
            
            # 获取价格信息
            if 'variants' in product_dict and product_dict['variants']:
                first_variant = product_dict['variants'][0]
                shopify_product['price'] = float(first_variant.get('price', 0.0))
                shopify_product['variants'] = product_dict['variants']
            
            shopify_products.append(shopify_product)
            logger.info(f"获取商品: {shopify_product['title']} (ID: {shopify_product['id']})")
        
        return shopify_products
    except Exception as e:
        logger.error(f"获取Shopify商品失败: {e}")
        import traceback
        traceback.print_exc()
        return []

async def import_products_to_database(shopify_products):
    """将商品导入到数据库"""
    async with async_session() as session:
        try:
            new_count = 0
            updated_count = 0
            skipped_count = 0
            
            from sqlmodel import select
            
            for product_data in shopify_products:
                # 检查是否已存在
                result = await session.execute(
                    select(Product).where(Product.shopify_product_id == product_data['id'])
                )
                existing_product = result.scalar_one_or_none()
                
                if existing_product:
                    # 更新现有产品
                    existing_product.name = product_data['title']
                    existing_product.description = product_data['description'][:255]  # 限制长度
                    existing_product.price = product_data['price']
                    existing_product.is_active = product_data['status'] == 'active'
                    existing_product.updated_at = datetime.utcnow()
                    
                    await session.commit()
                    updated_count += 1
                    logger.info(f"更新商品: {product_data['title']} (ID: {existing_product.id})")
                else:
                    # 创建新产品
                    new_product = Product(
                        name=product_data['title'],
                        description=product_data['description'][:255]  # 限制长度
                        if product_data['description'] else "新产品",
                        price=product_data['price'] if product_data['price'] > 0 else 99.99,  # 默认价格
                        category_id=1,  # 默认分类
                        stock_quantity=10,  # 默认库存
                        is_active=product_data['status'] == 'active',
                        shopify_product_id=product_data['id'],
                        created_at=datetime.utcnow(),
                        updated_at=datetime.utcnow()
                    )
                    
                    session.add(new_product)
                    await session.commit()
                    await session.refresh(new_product)
                    new_count += 1
                    logger.info(f"导入新商品: {product_data['title']} (数据库ID: {new_product.id})")
            
            # 显示统计信息
            logger.info("\n=== 导入统计 ===")
            logger.info(f"✓ 新增商品: {new_count}")
            logger.info(f"✓ 更新商品: {updated_count}")
            logger.info(f"✓ 跳过商品: {skipped_count}")
            logger.info(f"✓ 总处理商品: {len(shopify_products)}")
            logger.info("\n请刷新后端管理页面查看更新后的商品列表")
            
        except Exception as e:
            logger.error(f"导入商品到数据库失败: {e}")
            await session.rollback()
            import traceback
            traceback.print_exc()
        finally:
            await session.close()

async def main():
    """主函数"""
    logger.info("=== Shopify新商品导入工具 ===")
    
    # 设置Shopify连接
    if not setup_shopify_connection():
        logger.error("无法连接到Shopify，导入失败")
        return
    
    try:
        # 获取Shopify商品
        shopify_products = get_shopify_products()
        
        if not shopify_products:
            logger.error("未获取到任何Shopify商品")
            return
        
        # 导入到数据库
        await import_products_to_database(shopify_products)
        
    finally:
        # 清理会话
        try:
            shopify.ShopifyResource.clear_session()
            logger.info("已清理Shopify会话")
        except:
            pass

if __name__ == "__main__":
    asyncio.run(main())